package com.edu.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.card.CardInfoVO;
import com.edu.framework.websocket.message.card.TapCardRequest;
import com.edu.framework.websocket.message.card.TapVO;
import com.edu.framework.websocket.service.CardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class TapCardRequestHandler implements IHandler<TapCardRequest> {

    @Autowired
    private CardService cardService;

    @Override
    public void execute(WebSocketSession session, TapCardRequest message) {
        if (message == null) {
            return;
        }
        log.info(JSONObject.toJSONString(message));
        Map<String, TapVO> data = message.getData();
        TapVO tapVO = data.get(TapCardRequest.RESP_KEY);
        Response<CardInfoVO> response = cardService.charge(tapVO, false, 1);
        log.info(JSONObject.toJSONString(response));
        try {
            WebSocketHolder.send(session, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public String getType() {
        return TapCardRequest.TYPE;
    }


}
